package com.hmdp.interceptor;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.utils.UserHolder;
import net.sf.jsqlparser.util.validation.metadata.NamedObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.RequestToViewNameTranslator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Set;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * 第二层拦截器，用于拦截需要登录的接口。
 */
@Component
public class CheckUserLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果登录过的话，在第一层拦截器，就会把UserDto存入ThreadLocal中，因此这里直接取ThreadLocal即可
        UserDTO userDTO = UserHolder.getUser();
        if (userDTO == null) {
            // 设置状态码，前端如果收到状态码为 401 的请求，就会自动跳转到登录页面上面
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
